const MYAPP = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    cartsList: [],
    isChecked: true,
    allCheckPrice: 0
  },

  getAllCheckPrice: function() {
    var price = 0

    this.data.cartsList.forEach(item => {
      if(item.isChecked) {
        price += item.price * item.count
      }
    })

    this.setData({
      allCheckPrice: price * 100
    })
  },

  isCheckedTestFn: function() {
    var flag = this.data.cartsList.some(item => { if(!item.isChecked) return true })
    
    if (flag) {
      this.setData({
        isChecked: false
      })
      return 
    }
    
    this.setData({
      isChecked: true
    })
  },

  changeCount(event) {
    MYAPP.changeCartsList(event.target.dataset.id, event.detail)
    this.getAllCheckPrice()
  },

  changeCheck: function(event) {
    var id = event.target.dataset.id
    var status = event.detail

    MYAPP.checkCartsList(id, status)

    var index = this.data.cartsList.findIndex(item => item.id === id)

    this.data.cartsList[index].isChecked = status

    this.setData({
      cartsList: this.data.cartsList
    })

    this.isCheckedTestFn()
    this.getAllCheckPrice()

  },

  delCatesList: function(e){
    var index = this.data.cartsList.findIndex(item => item.id === e.target.dataset.id)

    this.data.cartsList.splice(index, 1)

    this.setData({
      cartsList: this.data.cartsList
    })

    MYAPP.delCartsList(e.target.dataset.id)

    this.getAllCheckPrice()
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.setData({
      cartsList: MYAPP.globalData.cartsList
    })

    this.isCheckedTestFn()
    this.getAllCheckPrice()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})